import cv2  
import numpy as np  
import os
from PIL import Image
print("开始转换")
# Gamma校正函数  
def gamma_correction(src, gamma):  
    lut = np.empty((1, 256), dtype=np.uint8)  
    for i in range(256):  
        lut[0, i] = np.clip(pow(i / 255.0, gamma) * 255.0, 0, 255).astype(np.uint8)  
    # 应用LUT到图像  
    dst = cv2.LUT(src, lut)  
    return dst  
  
# 主函数  
def main():  
    # 定义输入和输出文件夹  
    input_folder = './原始图片'  
    output_folder = './转换图片'  

    try:
        for root, _, files in os.walk(output_folder):  
            for file in files:
                os.remove(output_folder+"/"+file)
    except:
        print("移除过期结果失败..")
        
    # 确保输出文件夹存在  
    if not os.path.exists(output_folder):  
        os.makedirs(output_folder)  
  
    # 遍历输入文件夹中的所有文件  
    for filename in os.listdir(input_folder):  
        if filename.endswith('.jpg') or filename.endswith('.png'):  # 根据需要添加其他格式  
            # 读取图像  
            image_path = os.path.join(input_folder, filename)  
            #image = cv2.imread(image_path)
            image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), -1)
              
            if image is not None:  
                # 复制图像并转换为浮点数  
                src = image.copy().astype(np.float32) / 255.0  
  
                # 高斯模糊  
                gauss = cv2.GaussianBlur(src, (101, 101), 0)  
  
                # 除以高斯模糊结果  
                dst = cv2.divide(src, gauss, scale=255)  
  
                # 将结果转换为8位无符号整数  
                dst = np.clip(dst, 0, 255).astype(np.uint8)  
  
                # 应用Gamma校正  
                mat_gamma = gamma_correction(dst, 1.5)
                
                pil_img = Image.fromarray(cv2.cvtColor(mat_gamma, cv2.COLOR_BGR2RGB))  
  
                # 获取图像的宽度和高度  
                width, height = pil_img.size  
                  
                # 计算缩放因子  
                scale_factor = min(8192 / width, 8192 / height)  
                  
                # 计算放大后的新宽度和高度  
                enlarged_width = int(width * scale_factor)  
                enlarged_height = int(height * scale_factor)  
                  
                # 放大图像  
                enlarged_img = pil_img.resize((enlarged_width, enlarged_height), Image.LANCZOS)

                # 保存结果到输出文件夹  
                output_path = os.path.join(output_folder, filename)
                
                enlarged_img.save(output_path)  
                #cv2.imwrite(output_path, mat_gamma)
                #cv2.imencode('.png', mat_gamma)[1].tofile(output_path)
                print(f"{filename}输出成功！")
            else:  
                print(f"Error: Could not read the image {image_path}")  
  
# 调用主函数  
if __name__ == '__main__':  
    main()
